package qst.com.bacK.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import qst.com.bacK.exception.ExamException;
import qst.com.bacK.mapper.AssessmentsMapper;
import qst.com.bacK.mapper.ClassTeamMapper;
import qst.com.bacK.mapper.ScheduleMapper;
import qst.com.bacK.mapper.UserMapper;
import qst.com.bacK.pojo.entity.Schedule;
import qst.com.bacK.pojo.entity.User;
import qst.com.bacK.service.ScheduleService;

import java.sql.SQLException;
import java.util.List;

/**
 * Author:   msh
 * Date:     2024/10/14 下午2:29
 * Description:
 */

@Service
public class ScheduleServiceImpl implements ScheduleService {
    @Autowired
    private ScheduleMapper scheduleMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private AssessmentsMapper assessmentsMapper;
    @Autowired
    private ClassTeamMapper classTeamMapper;

    @Override
    public Schedule deleteSchedule(Integer id) {
        try {
            Schedule sche = scheduleMapper.findById(id);
            if (sche.getStatus() > 1) {
                throw new ExamException("只有未开始或作废的安排才能删除");
            }
            scheduleMapper.delete(sche.getId());
            return sche;
        } catch (SQLException e) {
            throw new ExamException("删除考试安排出错", e);
        }
    }

    @Override
    public Schedule findById(Integer id) {
        try {
            Schedule h = scheduleMapper.findById(id);
            h.setCreator(userMapper.findById(h.getCreatorId()));
            h.setAssessmentType(assessmentsMapper.findById(h.getAssessmentId()));
            h.setTeam(classTeamMapper.findById(h.getTeamId()));
            return h;
        } catch (SQLException e) {
            throw new ExamException("查询考试安排出错", e);
        }
    }

    @Override
    public List<Schedule> findByCreator(User user) {
        try {
            List<Schedule> scheduleList = scheduleMapper.findByCreatorId(user.getId());
            for (Schedule h : scheduleList) {
                h.setCreator(user);
                h.setAssessmentType(assessmentsMapper.findById(h.getAssessmentId()));
                h.setTeam(classTeamMapper.findById(h.getTeamId()));
            }
            return scheduleList;
        } catch (SQLException ex) {
            throw new ExamException("查询考试安排出错", ex);
        }
    }

    @Override
    public void saveSchedule(Schedule schedule) {
        try {
            scheduleMapper.save(schedule);
        } catch (SQLException e) {
            throw new ExamException("添加考试安排出错", e);
        }
    }

    @Override
    public void updateSchedule(Schedule schedule) {
        try {
            scheduleMapper.update(schedule);
        } catch (SQLException e) {
            throw new ExamException("更新考试安排出错", e);
        }
    }
}
